package com.Glow.reggie.service.impl;

import com.Glow.reggie.common.BaseContext;
import com.Glow.reggie.common.CustomException;
import com.Glow.reggie.entity.*;
import com.Glow.reggie.mapper.OrdersMapper;
import com.Glow.reggie.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author Glow
 * @Date 2022-08-05 21:31:54
 * @Description
 * @Version 1.0
 */
@Service
@Slf4j
@Transactional
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>implements OrdersService {
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Override
    @Transactional
    public void submit(Orders orders) {
        //日常localThread获取线程用户ID
        Long userId = BaseContext.getCurrentId();
        //查询购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        //如果你的购物车是空的，抛出异常！
        if(shoppingCartList.size() ==0 ||shoppingCartList == null)
        {
            throw new CustomException("购物车为空，无法下单！ ");
        }
        //后台还需要核算购物车金额，防止被恶意篡改
        AtomicInteger amount = new AtomicInteger(0);//原子类，用来存放金额,保护在多线程高并发环境下的安全，线程独享数据
        long orderId = IdWorker.getId();//订单号
            List<OrderDetail> orderDetails = shoppingCartList.stream().map(item->{
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(orderId);
                orderDetail.setNumber(item.getNumber());
                orderDetail.setDishFlavor(item.getDishFlavor());
                orderDetail.setDishId(item.getDishId());
                orderDetail.setSetmealId(item.getSetmealId());
                orderDetail.setName(item.getName());
                orderDetail.setImage(item.getImage());
                orderDetail.setAmount(item.getAmount());
                amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
                return orderDetail;
            }).collect(Collectors.toList());
        //查询用户信息
        User user = new User();
        user = userService.getById(userId);
        //获取选中地址簿信息
        AddressBook addressBook = new AddressBook();
        addressBook = addressBookService.getById(orders.getAddressBookId());
        if(addressBook == null)
        {
            throw new CustomException("地址信息有错误，无法下单！ ");
        }


        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        this.save(orders);
        orderDetailService.saveBatch(orderDetails);
        //清除购物车数据，因为生成了订单
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
    }
}
